<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>React之React Router 4（十一） | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="react,Router,">
  

  <meta name="description" content="一、React-router V4版本修改内容及一些坑1、所有组件更改为从react-router-dom导入 //v2import &amp;#123;Router,Route,hashHistory&amp;#125; from &apos;react-router&apos;;// 4.xx写法//v4import &amp;#123;Route,BrowserRouter as Router, Switch&amp;#125; from &apos;">
<meta name="keywords" content="react,Router">
<meta property="og:type" content="article">
<meta property="og:title" content="React之React Router 4（十一）">
<meta property="og:url" content="http://blog.poetries.top/2017/11/19/react-study-router-4-xx/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、React-router V4版本修改内容及一些坑1、所有组件更改为从react-router-dom导入 //v2import &amp;#123;Router,Route,hashHistory&amp;#125; from &apos;react-router&apos;;// 4.xx写法//v4import &amp;#123;Route,BrowserRouter as Router, Switch&amp;#125; from &apos;">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/468.png">
<meta property="og:updated_time" content="2020-08-15T04:25:31.930Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="React之React Router 4（十一）">
<meta name="twitter:description" content="一、React-router V4版本修改内容及一些坑1、所有组件更改为从react-router-dom导入 //v2import &amp;#123;Router,Route,hashHistory&amp;#125; from &apos;react-router&apos;;// 4.xx写法//v4import &amp;#123;Route,BrowserRouter as Router, Switch&amp;#125; from &apos;">
<meta name="twitter:image" content="https://poetries1.gitee.io/img-repo/2019/10/468.png">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、React-router-V4版本修改内容及一些坑"><span class="toc-text">一、React-router V4版本修改内容及一些坑</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、安装"><span class="toc-text">二、安装</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三、路由器-Router"><span class="toc-text">三、路由器(Router)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#四、历史-History"><span class="toc-text">四、历史(History)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#五、渲染"><span class="toc-text">五、渲染</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#六、-lt-App-gt"><span class="toc-text">六、&lt;App&gt;</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#七、路由-Route"><span class="toc-text">七、路由(Route)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#八、inclusive-routing"><span class="toc-text">八、inclusive routing</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#九、Exclusive-Routing"><span class="toc-text">九、Exclusive Routing</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十、Index-Routes”-和-“Not-Found”"><span class="toc-text">十、Index Routes” 和 “Not Found”</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十一、Link"><span class="toc-text">十一、Link</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十二、Match"><span class="toc-text">十二、Match</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十三、Authorized-Route"><span class="toc-text">十三、Authorized Route</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十四、-lt-Link-gt"><span class="toc-text">十四、&lt;Link&gt;</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十五、-lt-Switch-gt"><span class="toc-text">十五、&lt;Switch&gt;</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十六、更多参考"><span class="toc-text">十六、更多参考</span></a></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-react-study-router-4-xx" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">React之React Router 4（十一）</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2017.11.20</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 5.6k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 26分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h2 id="一、React-router-V4版本修改内容及一些坑"><a href="#一、React-router-V4版本修改内容及一些坑" class="headerlink" title="一、React-router V4版本修改内容及一些坑"></a>一、React-router V4版本修改内容及一些坑</h2><p><strong>1、所有组件更改为从react-router-dom导入</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//v2</span></span><br><span class="line"><span class="keyword">import</span> &#123;Router,Route,hashHistory&#125; <span class="keyword">from</span> <span class="string">'react-router'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 4.xx写法</span></span><br><span class="line"><span class="comment">//v4</span></span><br><span class="line"><span class="keyword">import</span> &#123;Route,BrowserRouter <span class="keyword">as</span> Router, Switch&#125; <span class="keyword">from</span> <span class="string">'react-router-dom'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 如果搭配redux，你还需要使用react-router-redux</span></span><br></pre></td></tr></table></figure>
<p><strong>2、将所有<router>替换为<browserrouter></browserrouter></router></strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//v2</span></span><br><span class="line"> &lt;Router history=&#123;hashHistory&#125;&gt;</span><br><span class="line">  &lt;Route path=<span class="string">"/"</span> component=&#123;PCIndex&#125;&gt;&lt;<span class="regexp">/Route&gt;</span></span><br><span class="line"><span class="regexp">  &lt;Route path="/</span>details/:uniqueky<span class="string">" component=&#123;PCNewsDetails&#125;&gt;&lt;/Route&gt;</span></span><br><span class="line"><span class="string">  &lt;Route path="</span>/usercenter<span class="string">" component=&#123;PCUserCenter&#125;&gt;&lt;/Route&gt;</span></span><br><span class="line"><span class="string"> &lt;/Router&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>现在需要更改为<code>BrowserRouter</code></p>
</blockquote>
<ul>
<li>这里的代码不仅仅是将<code>Router</code>替换为<code>BrowserRouter</code>,而且还把所有的<code>Route</code>中用<code>Switch</code>包裹起来.</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//v4</span></span><br><span class="line">&lt;BrowserRouter&gt;</span><br><span class="line">  &lt;Switch&gt;</span><br><span class="line">   &lt;Route exact path=<span class="string">"/"</span> component=&#123;MobileIndex&#125;&gt;&lt;<span class="regexp">/Route&gt;</span></span><br><span class="line"><span class="regexp">   &lt;Route path="/</span>details/:uniqueky<span class="string">" component=&#123;MobileNewsDetails&#125;&gt;&lt;/Route&gt;</span></span><br><span class="line"><span class="string">   &lt;Route path="</span>/usercenter<span class="string">" component=&#123;MobileUserCenter&#125;&gt;&lt;/Route&gt;</span></span><br><span class="line"><span class="string">  &lt;/Switch&gt;</span></span><br><span class="line"><span class="string"> &lt;/BrowserRouter&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>3、<browserrouter>只能有一个子节点</browserrouter></strong></p>
<blockquote>
<p><code>&lt;BroserRouter&gt;</code>只能有一个子节点,所以官网建议的是使用<code>&lt;Switch&gt;</code>进行包裹</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// v3</span></span><br><span class="line">&lt;Route path=<span class="string">'/'</span> component=&#123;App&#125;&gt;</span><br><span class="line"> &lt;IndexRoute component=&#123;Home&#125; /&gt;</span><br><span class="line"> &lt;Route path=<span class="string">'about'</span> component=&#123;About&#125; /&gt;</span><br><span class="line"> &lt;Route path=<span class="string">'contact'</span> component=&#123;Contact&#125; /&gt;</span><br><span class="line">&lt;<span class="regexp">/Route&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// v4</span></span><br><span class="line"><span class="keyword">const</span> App = <span class="function"><span class="params">()</span> =&gt;</span> (</span><br><span class="line"> &lt;Switch&gt;</span><br><span class="line">  &lt;Route exact path=<span class="string">'/'</span> component=&#123;Home&#125; /&gt;</span><br><span class="line">  &lt;Route path=<span class="string">'/about'</span> component=&#123;About&#125; /&gt;</span><br><span class="line">  &lt;Route path=<span class="string">'/contact'</span> component=&#123;Contact&#125; /&gt;</span><br><span class="line"> &lt;<span class="regexp">/Switch&gt;</span></span><br><span class="line"><span class="regexp">)</span></span><br></pre></td></tr></table></figure>
<p><strong>4、最坑的地方:在当前目录下的文件路径不再使用<code>./</code>, 而是直接用<code>/.</code></strong></p>
<blockquote>
<p>在进行文件引用的时候 ,<code>./src/js</code>的写法需要更改文’<code>/src/js</code>‘, 这是更改之后最坑的地方</p>
</blockquote>
<h2 id="二、安装"><a href="#二、安装" class="headerlink" title="二、安装"></a>二、安装</h2><blockquote>
<p><code>react-router-dom</code>暴露出<code>react-router</code>中暴露的对象与方法，因此你只需要安装并引用<code>react-router-dom</code>即可</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">npm install --save react-router-dom</span><br></pre></td></tr></table></figure>
<h2 id="三、路由器-Router"><a href="#三、路由器-Router" class="headerlink" title="三、路由器(Router)"></a>三、路由器(Router)</h2><blockquote>
<p>在你开始项目前，你需要决定你使用的路由器的类型。对于网页项目，存在<code>&lt;BrowserRouter&gt;</code>与<code>&lt;HashRouter&gt;</code>两种组件。当存在服务器来管理动态请求时，需要使用<code>&lt;BrowserRouter&gt;</code>组件，而<code>&lt;HashRouter&gt;</code>被用于静态网站。通常，我们更倾向选择<code>&lt;BrowserRouter&gt;</code>，但如果你的网站仅用来呈现静态文件，那么<code>&lt;HashRouter&gt;</code>将会是一个好选择</p>
</blockquote>
<h2 id="四、历史-History"><a href="#四、历史-History" class="headerlink" title="四、历史(History)"></a>四、历史(History)</h2><blockquote>
<p>每个路由器都会创建一个<code>history</code>对象并用其保持追踪当前location[注1]并且在有变化时对网站进行重新渲染。这个<code>history</code>对象保证了<code>React Router</code>提供的其他组件的可用性，所以其他组件必须在<code>router</code>内部渲染。一个<code>React Router</code>组件如果向父级上追溯却找不到<code>router</code>组件，那么这个组件将无法正常工作</p>
</blockquote>
<h2 id="五、渲染"><a href="#五、渲染" class="headerlink" title="五、渲染"></a>五、渲染<router></router></h2><blockquote>
<p>路由器组件无法接受两个及以上的子元素。基于这种限制的存在，创建一个<code>&lt;App&gt;</code>组件来渲染应用其余部分是一个有效的方法</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; BrowserRouter &#125; <span class="keyword">from</span> <span class="string">'react-router-dom'</span></span><br><span class="line">ReactDOM.render((</span><br><span class="line">  &lt;BrowserRouter&gt;</span><br><span class="line">    &lt;App /&gt;</span><br><span class="line">  &lt;<span class="regexp">/BrowserRouter&gt;</span></span><br><span class="line"><span class="regexp">), document.getElementById('root'))</span></span><br></pre></td></tr></table></figure>
<h2 id="六、-lt-App-gt"><a href="#六、-lt-App-gt" class="headerlink" title="六、&lt;App&gt;"></a>六、<code>&lt;App&gt;</code></h2><blockquote>
<p>应用通过<code>&lt;App&gt;</code>组件定义。简化一下，我们将应用拆分成两个部分。<code>&lt;Header&gt;</code>组件包含网站的导航链接。<code>&lt;Main&gt;</code>组件则呈现其余内容</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> App = <span class="function"><span class="params">()</span> =&gt;</span> (</span><br><span class="line">  &lt;div&gt;</span><br><span class="line">    &lt;Header /&gt;</span><br><span class="line">    &lt;Main /&gt;</span><br><span class="line">  &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">)</span></span><br></pre></td></tr></table></figure>
<h2 id="七、路由-Route"><a href="#七、路由-Route" class="headerlink" title="七、路由(Route)"></a>七、路由(Route)</h2><blockquote>
<p><code>&lt;Route&gt;</code>组件是<code>React Router</code>中主要的结构单元。在任意位置只要匹配了<code>URL</code>的路径名(<code>pathname</code>)你就可以创建<code>&lt;Route&gt;</code>元素进行渲染</p>
</blockquote>
<p><strong>1、路径(Path)</strong></p>
<blockquote>
<p><code>&lt;Route&gt;</code>接受一个数为<code>string</code>类型的<code>path</code>，该值路由匹配的路径名的类型。例如：<code>&lt;Route path=&#39;/roster&#39;/&gt;</code>会匹配以<code>/roster</code>开头的路径名。在当前<code>path</code>参数与当前<code>location</code>的路径相匹配时，路由就会开始渲染<code>React</code>元素。若不匹配，路由不会进行任何操作</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&lt;Route path=<span class="string">'/roster'</span>/&gt;</span><br><span class="line"><span class="comment">// 当路径名为'/'时, path不匹配</span></span><br><span class="line"><span class="comment">// 当路径名为'/roster'或'/roster/2'时, path匹配</span></span><br><span class="line"><span class="comment">// 当你只想匹配'/roster'时，你需要使用"exact"参数</span></span><br><span class="line"><span class="comment">// 则路由仅匹配'/roster'而不会匹配'/roster/2'</span></span><br><span class="line">&lt;Route exact path=<span class="string">'/roster'</span>/&gt;</span><br></pre></td></tr></table></figure>
<ul>
<li>注意：在匹配路由时，<code>React Router</code>只关注<code>location</code>的路径名。当<code>URL</code>如下时</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">http:<span class="comment">//www.example.com/my-projects/one?extra=false</span></span><br></pre></td></tr></table></figure>
<ul>
<li><code>React Router</code>去匹配的只是<code>&#39;/my-projects/one&#39;</code>这一部分</li>
</ul>
<p><strong>2、匹配路径</strong></p>
<blockquote>
<p><code>path-to-regexp</code>包用来决定<code>route</code>元素的<code>path</code>参数与当前<code>location</code>是否匹配。它将路径字符串编译成正则表达式，并与当前<code>location</code>的路径名进行匹配比较</p>
</blockquote>
<ul>
<li>当路由地址匹配成功后，会创建一个含有以下属性的<code>match</code>对象：<ul>
<li><code>url</code> ：与当前<code>location</code>路径名所匹配部分</li>
<li><code>path</code>：路由的地址</li>
<li><code>isExact</code> ：<code>path</code> 是否等于 <code>pathname</code></li>
<li><code>params</code>：从<code>path-to-regexp</code>获取的路径中取出的值都被包含在这个对象中</li>
</ul>
</li>
</ul>
<p>使用<a href="https://pshrmn.github.io/route-tester/#/" target="_blank" rel="noopener">route tester</a>这款工具来对路由与URL进行检验</p>
<p><strong>3、创建你的路由</strong></p>
<blockquote>
<p>可以在路由器(router)组件中的任意位置创建多个<code>&lt;Route&gt;</code>，但通常我们会把它们放在同一个位置。使用<code>&lt;Switch&gt;</code>组件来包裹一组<code>&lt;Route&gt;</code>。<code>&lt;Switch&gt;</code>会遍历自身的子元素（即路由）并对第一个匹配当前路径的元素进行渲染</p>
</blockquote>
<ul>
<li>我们希望匹配一下路径<ul>
<li><code>/</code>：主页</li>
<li><code>/roster</code>： 团体列表</li>
<li><code>/roster/:number</code>：运动员页面，使用运动员的编号作为标识</li>
<li><code>/schedule</code>：团队的赛程表</li>
</ul>
</li>
</ul>
<p>为了在应用中能匹配路径，在创建<code>&lt;Route&gt;</code>元素时必须带有需要匹配的<code>path</code>作为参数</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&lt;Switch&gt;</span><br><span class="line">  &lt;Route exact path=<span class="string">'/'</span> component=&#123;Home&#125;/&gt;</span><br><span class="line">  &#123;<span class="comment">/* both /roster and /roster/:number begin with /roster */</span>&#125;</span><br><span class="line">  &lt;Route path=<span class="string">'/roster'</span> component=&#123;Roster&#125;/&gt;</span><br><span class="line">  &lt;Route path=<span class="string">'/schedule'</span> component=&#123;Schedule&#125;/&gt;</span><br><span class="line">&lt;<span class="regexp">/Switch&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>4、<code>&lt;Route&gt;</code>是如何渲染的？</strong></p>
<blockquote>
<p>当一个路由的<code>path</code>匹配成功后，路由用来确定渲染结果的参数有三种。只需要提供其中一个即可</p>
</blockquote>
<ul>
<li><code>component</code> ： 一个<code>React</code>组件。当带有<code>component</code>参数的<code>route</code>匹配成功后，<code>route</code>会返回一个新的元素，其为<code>component</code>参数所对应的<code>React</code>组件（使用<code>React.createElement</code>创建）。</li>
<li><code>render</code> ： 一个返回<code>React element</code>的函数。当匹配成功后调用该函数。该过程与传入<code>component</code>参数类似，并且对于行级渲染与需要向元素传入额外参数的操作会更有用。</li>
<li><code>children</code> ： 一个返回<code>React element</code>的函数。与上述两个参数不同，无论<code>route</code>是否匹配当前<code>location</code>，其都会被渲染</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&lt;Route path=<span class="string">'/page'</span> component=&#123;Page&#125; /&gt;</span><br><span class="line"><span class="keyword">const</span> extraProps = &#123; <span class="attr">color</span>: <span class="string">'red'</span> &#125;</span><br><span class="line">&lt;Route path=<span class="string">'/page'</span> render=&#123;(props) =&gt; (</span><br><span class="line">  &lt;Page &#123;...props&#125; data=&#123;extraProps&#125;/&gt;</span><br><span class="line">)&#125;/&gt;</span><br><span class="line">&lt;Route path=<span class="string">'/page'</span> children=&#123;(props) =&gt; (</span><br><span class="line">  props.match</span><br><span class="line">    ? <span class="xml"><span class="tag">&lt;<span class="name">Page</span> &#123;<span class="attr">...props</span>&#125;/&gt;</span></span></span><br><span class="line">    : <span class="xml"><span class="tag">&lt;<span class="name">EmptyPage</span> &#123;<span class="attr">...props</span>&#125;/&gt;</span></span></span><br><span class="line">)&#125;/&gt;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>通常<code>component</code>参数与<code>render</code>参数被更经常地使用。<code>children</code>参数偶尔会被使用，它更常用在<code>path</code>无法匹配时呈现的’空’状态。在本例中并不会有额外的状态，所以我们将使用<code>&lt;Route&gt;</code>的<code>component</code>参数</p>
</blockquote>
<ul>
<li>通过<code>&lt;Route&gt;</code>渲染的元素会被传入一些参数。分别是<code>match</code>对象，当前<code>location</code>对象以及<code>history</code>对象（由<code>router</code>创建）</li>
</ul>
<p><strong>5、<code>&lt;Main&gt;</code></strong></p>
<blockquote>
<p>现在我们清楚了根路由的结构，我们需要实际渲染我们的路由。对于这个应用，我们将会在<code>&lt;Main&gt;</code>组件中渲染<code>&lt;Switch&gt;</code>与<code>&lt;Route&gt;</code>，这一过程会将<code>route</code>匹配生成的<code>HTML</code>放在<code>&lt;main&gt;</code>节点中</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Switch, Route &#125; <span class="keyword">from</span> <span class="string">'react-router-dom'</span></span><br><span class="line"><span class="keyword">const</span> Main = <span class="function"><span class="params">()</span> =&gt;</span> (</span><br><span class="line">  &lt;main&gt;</span><br><span class="line">    &lt;Switch&gt;</span><br><span class="line">      &lt;Route exact path=<span class="string">'/'</span> component=&#123;Home&#125;/&gt;</span><br><span class="line">      &lt;Route path=<span class="string">'/roster'</span> component=&#123;Roster&#125;/&gt;</span><br><span class="line">      &lt;Route path=<span class="string">'/schedule'</span> component=&#123;Schedule&#125;/&gt;</span><br><span class="line">    &lt;<span class="regexp">/Switch&gt;</span></span><br><span class="line"><span class="regexp">  &lt;/m</span>ain&gt;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>注意</strong>：主页路由包含额外参数。该参数用来保证路由能准确匹配<code>path</code></li>
</ul>
<p><strong>6、嵌套路由</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// v3</span></span><br><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">"react"</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; render &#125; <span class="keyword">from</span> <span class="string">"react-dom"</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; Router, Route, IndexRoute, Link, browserHistory &#125; <span class="keyword">from</span> <span class="string">"react-router"</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> PrimaryLayout = <span class="function"><span class="params">props</span> =&gt;</span></span><br><span class="line">  &lt;div className=<span class="string">"primary-layout"</span>&gt;</span><br><span class="line">    &lt;header&gt;Our React Router <span class="number">3</span> App&lt;<span class="regexp">/header&gt;</span></span><br><span class="line"><span class="regexp">    &lt;ul&gt;</span></span><br><span class="line"><span class="regexp">      &lt;li&gt;</span></span><br><span class="line"><span class="regexp">        &lt;Link to="/</span><span class="string">"&gt;Home&lt;/Link&gt;</span></span><br><span class="line"><span class="string">      &lt;/li&gt;</span></span><br><span class="line"><span class="string">      &lt;li&gt;</span></span><br><span class="line"><span class="string">        &lt;Link to="</span>/user<span class="string">"&gt;User&lt;/Link&gt;</span></span><br><span class="line"><span class="string">      &lt;/li&gt;</span></span><br><span class="line"><span class="string">    &lt;/ul&gt;</span></span><br><span class="line"><span class="string">    &lt;main&gt;</span></span><br><span class="line"><span class="string">      &#123;props.children&#125;</span></span><br><span class="line"><span class="string">    &lt;/main&gt;</span></span><br><span class="line"><span class="string">  &lt;/div&gt;;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">const HomePage = () =&gt; &lt;h1&gt;Home Page&lt;/h1&gt;;</span></span><br><span class="line"><span class="string">const UsersPage = () =&gt; &lt;h1&gt;User Page&lt;/h1&gt;;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">const App = () =&gt;</span></span><br><span class="line"><span class="string">  &lt;Router history=&#123;browserHistory&#125;&gt;</span></span><br><span class="line"><span class="string">    &lt;Route path="</span>/<span class="string">" component=&#123;PrimaryLayout&#125;&gt;</span></span><br><span class="line"><span class="string">      &lt;IndexRoute component=&#123;HomePage&#125; /&gt;</span></span><br><span class="line"><span class="string">      &lt;Route path="</span>/user<span class="string">" component=&#123;UsersPage&#125; /&gt;</span></span><br><span class="line"><span class="string">    &lt;/Route&gt;</span></span><br><span class="line"><span class="string">  &lt;/Router&gt;;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">render(&lt;App /&gt;, document.getElementById("</span>root<span class="string">"));</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>上面代码中有几个关键的点在 V4 中就不复存在了</strong><ul>
<li>集中式 <code>router</code></li>
<li>通过 <code>&lt;Route&gt;</code> 嵌套，实现<code>Layout</code> 和 <code>page</code> 嵌套</li>
<li><code>Layout</code> 和 <code>page</code>组件 是作为 <code>router</code> 的一部分</li>
</ul>
</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// v4</span></span><br><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">"react"</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; render &#125; <span class="keyword">from</span> <span class="string">"react-dom"</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; BrowserRouter, Route, Link &#125; <span class="keyword">from</span> <span class="string">"react-router-dom"</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> PrimaryLayout = <span class="function"><span class="params">()</span> =&gt;</span></span><br><span class="line">  &lt;div className=<span class="string">"primary-layout"</span>&gt;</span><br><span class="line">    &lt;header&gt;Our React Router <span class="number">4</span> App&lt;<span class="regexp">/header&gt;</span></span><br><span class="line"><span class="regexp">    &lt;ul&gt;</span></span><br><span class="line"><span class="regexp">      &lt;li&gt;</span></span><br><span class="line"><span class="regexp">        &lt;Link to="/</span><span class="string">"&gt;Home&lt;/Link&gt;</span></span><br><span class="line"><span class="string">      &lt;/li&gt;</span></span><br><span class="line"><span class="string">      &lt;li&gt;</span></span><br><span class="line"><span class="string">        &lt;Link to="</span>/User<span class="string">"&gt;User&lt;/Link&gt;</span></span><br><span class="line"><span class="string">      &lt;/li&gt;</span></span><br><span class="line"><span class="string">    &lt;/ul&gt;</span></span><br><span class="line"><span class="string">    &lt;main&gt;</span></span><br><span class="line"><span class="string">      &lt;Route path="</span>/<span class="string">" exact component=&#123;HomePage&#125; /&gt;</span></span><br><span class="line"><span class="string">      &lt;Route path="</span>/user<span class="string">" component=&#123;UsersPage&#125; /&gt;</span></span><br><span class="line"><span class="string">    &lt;/main&gt;</span></span><br><span class="line"><span class="string">  &lt;/div&gt;;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">const HomePage = () =&gt; &lt;h1&gt;Home Page&lt;/h1&gt;;</span></span><br><span class="line"><span class="string">const UsersPage = () =&gt; &lt;h1&gt;User Page&lt;/h1&gt;;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">const App = () =&gt;</span></span><br><span class="line"><span class="string">  &lt;BrowserRouter&gt;</span></span><br><span class="line"><span class="string">    &lt;PrimaryLayout /&gt;</span></span><br><span class="line"><span class="string">  &lt;/BrowserRouter&gt;;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">render(&lt;App /&gt;, document.getElementById("</span>root<span class="string">"));</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>首先，<code>V3</code> 中的 <code>router</code> 不在了，在 <code>V3</code> 中，我们是将整个庞大的<code>router</code> 直接丢给 <code>DOM</code>，而在 <code>V4</code> 中，除了 <code>BrowserRouter</code>， 我们丢给 <code>DOM</code> 的是我们的应用程序本身</p>
</blockquote>
<ul>
<li><code>V4</code>中，我们不再使用 <code>{props.children}</code> 来嵌套组件了，替代的 <code>&lt;Route&gt;</code>，当 <code>route</code>匹配时，子组件会被渲染到 <code>&lt;Route&gt;</code>书写的地方</li>
</ul>
<ul>
<li>基本使用</li>
</ul>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/468.png" alt></p>
<blockquote>
<p><code>react-router 4.0</code> 对于接受参数采用 <code>{ this.props.match.params.id }</code> 如下例子：<code>&lt;Route path=&quot;list/:id&quot;&gt;&lt;/Router&gt;</code>、 <code>&lt;Link to=&quot;list/123456&quot;&gt;&lt;/Link&gt;</code></p>
</blockquote>
<ul>
<li>一个完整的嵌套路由的例子</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// import &#123; Router, Route, Link, Switch &#125; from ‘react-router‘;</span></span><br><span class="line"><span class="keyword">import</span> &#123;</span><br><span class="line">  HashRouter,</span><br><span class="line">  Route,</span><br><span class="line">  Link,</span><br><span class="line">  Switch</span><br><span class="line">&#125; <span class="keyword">from</span> ‘react-router-dom‘;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">App</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</span><br><span class="line">  render() &#123;</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      &lt;div&gt;</span><br><span class="line">        &lt;h1&gt;App&lt;<span class="regexp">/h1&gt;</span></span><br><span class="line"><span class="regexp">        &lt;ul&gt;</span></span><br><span class="line"><span class="regexp">          &lt;li&gt;&lt;Link to="/</span><span class="string">"&gt;Home&lt;/Link&gt;&lt;/li&gt;</span></span><br><span class="line"><span class="string">          &lt;li&gt;&lt;Link to="</span>/about<span class="string">"&gt;About&lt;/Link&gt;&lt;/li&gt;</span></span><br><span class="line"><span class="string">          &lt;li&gt;&lt;Link to="</span>/inbox<span class="string">"&gt;Inbox&lt;/Link&gt;&lt;/li&gt;</span></span><br><span class="line"><span class="string">        &lt;/ul&gt;</span></span><br><span class="line"><span class="string">        &#123;this.props.children&#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">      &lt;/div&gt;</span></span><br><span class="line"><span class="string">    );</span></span><br><span class="line"><span class="string">  &#125;</span></span><br><span class="line"><span class="string">&#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">const About = () =&gt; (</span></span><br><span class="line"><span class="string">  &lt;div&gt;</span></span><br><span class="line"><span class="string">    &lt;h3&gt;About&lt;/h3&gt;</span></span><br><span class="line"><span class="string">  &lt;/div&gt;</span></span><br><span class="line"><span class="string">)</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">const Home = () =&gt; (</span></span><br><span class="line"><span class="string">  &lt;div&gt;</span></span><br><span class="line"><span class="string">    &lt;h3&gt;Home&lt;/h3&gt;</span></span><br><span class="line"><span class="string">  &lt;/div&gt;</span></span><br><span class="line"><span class="string">)</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">const Message = (&#123; match &#125;) =&gt; (</span></span><br><span class="line"><span class="string">  &lt;div&gt;</span></span><br><span class="line"><span class="string">    &lt;h3&gt;new messages&lt;/h3&gt;</span></span><br><span class="line"><span class="string">    &lt;h3&gt;&#123;match.params.id&#125;&lt;/h3&gt;</span></span><br><span class="line"><span class="string">  &lt;/div&gt;</span></span><br><span class="line"><span class="string">)</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">const Inbox = (&#123; match &#125;) =&gt; (</span></span><br><span class="line"><span class="string">  &lt;div&gt;</span></span><br><span class="line"><span class="string">    &lt;h2&gt;Topics&lt;/h2&gt;</span></span><br><span class="line"><span class="string">    &lt;Route path=&#123;`$&#123;match.url&#125;/messages/:id`&#125; component=&#123;Message&#125;/&gt;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">  &lt;/div&gt;</span></span><br><span class="line"><span class="string">) </span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">ReactDOM.render(</span></span><br><span class="line"><span class="string">  (&lt;HashRouter&gt;</span></span><br><span class="line"><span class="string">    &lt;App&gt;</span></span><br><span class="line"><span class="string">        &lt;Route exact path="</span>/<span class="string">" component=&#123;Home&#125; /&gt;</span></span><br><span class="line"><span class="string">        &lt;Route path="</span>/about<span class="string">" component=&#123;About&#125; /&gt;</span></span><br><span class="line"><span class="string">        &lt;Route path="</span>/inbox<span class="string">" component=&#123;Inbox&#125; /&gt;</span></span><br><span class="line"><span class="string">    &lt;/App&gt;</span></span><br><span class="line"><span class="string">  &lt;/HashRouter&gt;),</span></span><br><span class="line"><span class="string">  document.getElementById(‘root‘)</span></span><br><span class="line"><span class="string">);</span></span><br></pre></td></tr></table></figure>
<ul>
<li>嵌套布局</li>
</ul>
<blockquote>
<p>方式一</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> PrimaryLayout = <span class="function"><span class="params">props</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div className=<span class="string">"primary-layout"</span>&gt;</span><br><span class="line">      &lt;PrimaryHeader /&gt;</span><br><span class="line">      &lt;main&gt;</span><br><span class="line">        &lt;Switch&gt;</span><br><span class="line">          &lt;Route path=<span class="string">"/"</span> exact component=&#123;HomePage&#125; /&gt;</span><br><span class="line">          &lt;Route path=<span class="string">"/user"</span> exact component=&#123;BrowseUsersPage&#125; /&gt;</span><br><span class="line">          &lt;Route path=<span class="string">"/user/:userId"</span> component=&#123;UserProfilePage&#125; /&gt;</span><br><span class="line">          &lt;Route path=<span class="string">"/products"</span> exact component=&#123;BrowseProductsPage&#125; /&gt;</span><br><span class="line">          &lt;Route path=<span class="string">"/products/:productId"</span> component=&#123;ProductProfilePage&#125; /&gt;</span><br><span class="line">          &lt;Redirect to=<span class="string">"/"</span> /&gt;</span><br><span class="line">        &lt;<span class="regexp">/Switch&gt;</span></span><br><span class="line"><span class="regexp">      &lt;/m</span>ain&gt;</span><br><span class="line">    &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">  );</span></span><br><span class="line"><span class="regexp">&#125;;</span></span><br></pre></td></tr></table></figure>
<ul>
<li><code>userId</code> 通过 <code>props.match.params</code> 获取</li>
<li><code>props.match</code> 赋予给了 <code>&lt;Route&gt;</code> 中的任何组件。</li>
<li>除此之外，如果组件不通过<code>&lt;Route&gt;</code> 来渲染，要访问 <code>props.match</code>，可以使用 <code>withRouter()</code>高阶组件来实现</li>
</ul>
<blockquote>
<p>方式二</p>
</blockquote>
<ul>
<li>解决了第一种方式中的生命周期，重复渲染的问题</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> PrimaryLayout = <span class="function"><span class="params">props</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div className=<span class="string">"primary-layout"</span>&gt;</span><br><span class="line">      &lt;PrimaryHeader /&gt;</span><br><span class="line">      &lt;main&gt;</span><br><span class="line">        &lt;Switch&gt;</span><br><span class="line">          &lt;Route path=<span class="string">"/"</span> exact component=&#123;HomePage&#125; /&gt;</span><br><span class="line">          &lt;Route path=<span class="string">"/user"</span> component=&#123;UserSubLayout&#125; /&gt;</span><br><span class="line">          &lt;Route path=<span class="string">"/products"</span> component=&#123;ProductSubLayout&#125; /&gt;</span><br><span class="line">          &lt;Redirect to=<span class="string">"/"</span> /&gt;</span><br><span class="line">        &lt;<span class="regexp">/Switch&gt;</span></span><br><span class="line"><span class="regexp">      &lt;/m</span>ain&gt;</span><br><span class="line">    &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">  );</span></span><br><span class="line"><span class="regexp">&#125;;</span></span><br></pre></td></tr></table></figure>
<ul>
<li>我们用 <code>2</code>个 <code>routes</code> 替换之前的 <code>4</code>个<code>routes</code></li>
<li>注意，这里我们没有再使用 <code>exact</code>，因为，我们希望 <code>/user</code> 可以匹配任何以 <code>/user</code> 开始的 <code>route</code>，<code>products</code> 同理</li>
</ul>
<blockquote>
<p>使用这种策略，子布局也开始承担起了渲染 <code>routes</code> 的责任，现在，<code>UserSubLayout</code> 长这样</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> UserSubLayout = <span class="function"><span class="params">()</span> =&gt;</span></span><br><span class="line">  &lt;div className=<span class="string">"user-sub-layout"</span>&gt;</span><br><span class="line">    &lt;aside&gt;</span><br><span class="line">      &lt;UserNav /&gt;</span><br><span class="line">    &lt;<span class="regexp">/aside&gt;</span></span><br><span class="line"><span class="regexp">    &lt;div className="primary-content"&gt;</span></span><br><span class="line"><span class="regexp">      &lt;Switch&gt;</span></span><br><span class="line"><span class="regexp">        &lt;Route path="/u</span>ser<span class="string">" exact component=&#123;BrowseUsersPage&#125; /&gt;</span></span><br><span class="line"><span class="string">        &lt;Route path="</span>/user/:userId<span class="string">" component=&#123;UserProfilePage&#125; /&gt;</span></span><br><span class="line"><span class="string">      &lt;/Switch&gt;</span></span><br><span class="line"><span class="string">    &lt;/div&gt;</span></span><br><span class="line"><span class="string">  &lt;/div&gt;;</span></span><br></pre></td></tr></table></figure>
<ul>
<li>但有一点值得注意的是，<code>routes</code> 需要识别它的完整路径才能匹配，为了减少我们的重复输入，我们可以使用 <code>props.match.path</code>来代替</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> UserSubLayout = <span class="function"><span class="params">props</span> =&gt;</span></span><br><span class="line">  &lt;div className=<span class="string">"user-sub-layout"</span>&gt;</span><br><span class="line">    &lt;aside&gt;</span><br><span class="line">      &lt;UserNav /&gt;</span><br><span class="line">    &lt;<span class="regexp">/aside&gt;</span></span><br><span class="line"><span class="regexp">    &lt;div className="primary-content"&gt;</span></span><br><span class="line"><span class="regexp">      &lt;Switch&gt;</span></span><br><span class="line"><span class="regexp">        &lt;Route path=&#123;props.match.path&#125; exact component=&#123;BrowseUsersPage&#125; /</span>&gt;</span><br><span class="line">        &lt;Route</span><br><span class="line">          path=&#123;<span class="string">`<span class="subst">$&#123;props.match.path&#125;</span>/:userId`</span>&#125;</span><br><span class="line">          component=&#123;UserProfilePage&#125;</span><br><span class="line">        /&gt;</span><br><span class="line">      &lt;<span class="regexp">/Switch&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/</span>div&gt;</span><br><span class="line">  &lt;<span class="regexp">/div&gt;;</span></span><br></pre></td></tr></table></figure>
<p><strong>7、路径参数</strong></p>
<p>有时路径名中存在我们需要获取的参数。例如，在运动员界面，我们需要获取运动员的编号。我们可以向<code>route</code>的路径字符串中添加<code>path</code>参数</p>
<ul>
<li>如<code>&#39;/roster/:number&#39;</code>中<code>:number</code>这种写法意味着<code>/roster/</code>后的路径名将会被获取并存在<code>match.params.number</code>中。例如，路径名<code>&#39;/roster/6&#39;</code>会获取到一个对象</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&#123; <span class="attr">number</span>: <span class="string">'6'</span> &#125; <span class="comment">// 注获取的值是字符串类型的</span></span><br></pre></td></tr></table></figure>
<ul>
<li><code>&lt;Player&gt;</code>组件可以使用<code>props.match.params</code>对象来确定需要被渲染的运动员的数据</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 返回运动员对象的API</span></span><br><span class="line"><span class="keyword">import</span> PlayerAPI <span class="keyword">from</span> <span class="string">'./PlayerAPI'</span></span><br><span class="line"><span class="keyword">const</span> Player = <span class="function">(<span class="params">props</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">const</span> player = PlayerAPI.get(</span><br><span class="line">    <span class="built_in">parseInt</span>(props.match.params.number, <span class="number">10</span>)</span><br><span class="line">  )</span><br><span class="line">  <span class="keyword">if</span> (!player) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>Sorry, but the player was not found<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div&gt;</span><br><span class="line">      &lt;h1&gt;&#123;player.name&#125; (#&#123;player.number&#125;)&lt;/h1&gt;</span><br><span class="line">      &lt;h2&gt;&#123;player.position&#125;&lt;<span class="regexp">/h2&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/</span>div&gt;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>除了<code>&lt;Player&gt;</code>组件，我们的页面还包含<code>&lt;FullRoster&gt;</code>, <code>&lt;Schedule&gt;</code>以及 <code>&lt;Home&gt;</code>组件</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> FullRoster = <span class="function"><span class="params">()</span> =&gt;</span> (</span><br><span class="line">  &lt;div&gt;</span><br><span class="line">    &lt;ul&gt;</span><br><span class="line">      &#123;</span><br><span class="line">        PlayerAPI.all().map(<span class="function"><span class="params">p</span> =&gt;</span> (</span><br><span class="line">          &lt;li key=&#123;p.number&#125;&gt;</span><br><span class="line">            &lt;Link to=&#123;<span class="string">`/roster/<span class="subst">$&#123;p.number&#125;</span>`</span>&#125;&gt;&#123;p.name&#125;&lt;<span class="regexp">/Link&gt;</span></span><br><span class="line"><span class="regexp">          &lt;/</span>li&gt;</span><br><span class="line">        ))</span><br><span class="line">      &#125;</span><br><span class="line">    &lt;<span class="regexp">/ul&gt;</span></span><br><span class="line"><span class="regexp">  &lt;/</span>div&gt;</span><br><span class="line">)</span><br><span class="line"><span class="keyword">const</span> Schedule = <span class="function"><span class="params">()</span> =&gt;</span> (</span><br><span class="line">  &lt;div&gt;</span><br><span class="line">    &lt;ul&gt;</span><br><span class="line">      &lt;li&gt;<span class="number">6</span>/<span class="number">5</span> @ Evergreens&lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">      &lt;li&gt;6/</span><span class="number">8</span> vs Kickers&lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">      &lt;li&gt;6/</span><span class="number">14</span> @ United&lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/u</span>l&gt;</span><br><span class="line">  &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">)</span></span><br><span class="line"><span class="regexp">const Home = () =&gt; (</span></span><br><span class="line"><span class="regexp">  &lt;div&gt;</span></span><br><span class="line"><span class="regexp">    &lt;h1&gt;Welcome to the Tornadoes Website!&lt;/</span>h1&gt;</span><br><span class="line">  &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">)</span></span><br></pre></td></tr></table></figure>
<h2 id="八、inclusive-routing"><a href="#八、inclusive-routing" class="headerlink" title="八、inclusive routing"></a>八、inclusive routing</h2><blockquote>
<p>当访问 <code>/user</code> 时，两个组价都会被渲染</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">const PrimaryLayout = () =&gt;</span><br><span class="line">  &lt;div className=&quot;primary-layout&quot;&gt;</span><br><span class="line">    &lt;header&gt;</span><br><span class="line">      Our React Router 4 App</span><br><span class="line">      &lt;Route path=&quot;/user&quot; component=&#123;UsersMenu&#125; /&gt;</span><br><span class="line">    &lt;/header&gt;</span><br><span class="line">    &lt;main&gt;</span><br><span class="line">      &lt;Route path=&quot;/&quot; exact component=&#123;HomePage&#125; /&gt;</span><br><span class="line">      &lt;Route path=&quot;/user&quot; component=&#123;UsersPage&#125; /&gt;</span><br><span class="line">    &lt;/main&gt;</span><br><span class="line">  &lt;/div&gt;;</span><br></pre></td></tr></table></figure>
<h2 id="九、Exclusive-Routing"><a href="#九、Exclusive-Routing" class="headerlink" title="九、Exclusive Routing"></a>九、Exclusive Routing</h2><blockquote>
<p>如果你只想匹配一个 <code>route</code>，那么你也可以使用 <code>&lt;Switch&gt;</code> 来 <code>exclusive routing</code></p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> PrimaryLayout = <span class="function"><span class="params">()</span> =&gt;</span></span><br><span class="line">  &lt;div className=<span class="string">"primary-layout"</span>&gt;</span><br><span class="line">    &lt;PrimaryHeader /&gt;</span><br><span class="line">    &lt;main&gt;</span><br><span class="line">      &lt;Switch&gt;</span><br><span class="line">        &lt;Route path=<span class="string">"/"</span> exact component=&#123;HomePage&#125; /&gt;</span><br><span class="line">        &lt;Route path=<span class="string">"/user/add"</span> component=&#123;UserAddPage&#125; /&gt;</span><br><span class="line">        &lt;Route path=<span class="string">"/user"</span> component=&#123;UsersPage&#125; /&gt;</span><br><span class="line">        &lt;Redirect to=<span class="string">"/"</span> /&gt;</span><br><span class="line">      &lt;<span class="regexp">/Switch&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/m</span>ain&gt;</span><br><span class="line">  &lt;<span class="regexp">/div&gt;;</span></span><br></pre></td></tr></table></figure>
<ul>
<li>在 <code>&lt;Switch&gt;</code> 中只有一个 <code>&lt;Route&gt;</code> 会被渲染，另外，我们还是要给 <code>HomePage</code>所在 <code>&lt;Route&gt;</code>添加 <code>exact</code>，否则，在访问 <code>/user</code> 或 <code>/user/add</code>的时候还是会匹配到 <code>/</code>，从而，只渲染 H<code>omePage</code></li>
<li>我们将 <code>/user/add</code>放在 <code>/user</code> 前面是保证正确匹配的很有策略性的一步，因为，<code>/user/add</code>会同时匹配 <code>/user</code>和 <code>/user/add</code></li>
<li>如果我们给每一个 <code>&lt;Route&gt;</code>都添加一个 <code>exact</code>，那就不用考虑上面的 策略 了，但不管怎样，现在至少知道了我们还有其它选择</li>
<li><code>&lt;Redirect&gt;</code>组件不用多说，执行浏览器重定向，但它在 <code>&lt;Switch&gt;</code> 中时，<code>&lt;Redirect&gt;</code>组件只会在 <code>routes</code> 匹配不成功的情况下渲染</li>
</ul>
<h2 id="十、Index-Routes”-和-“Not-Found”"><a href="#十、Index-Routes”-和-“Not-Found”" class="headerlink" title="十、Index Routes” 和 “Not Found”"></a>十、Index Routes” 和 “Not Found”</h2><blockquote>
<p><code>V4</code> 中也没有 <code>&lt;IndexRoute&gt;</code>，但 <code>&lt;Route exact&gt;</code>可以实现相同的功能，或者 <code>&lt;Switch&gt;</code>和 <code>&lt;Redirect&gt;</code> 重定向到默认的有效路径，甚至一个找不到的页面</p>
</blockquote>
<h2 id="十一、Link"><a href="#十一、Link" class="headerlink" title="十一、Link"></a>十一、Link</h2><blockquote>
<p>现在，我们应用需要在各个页面间切换。如果使用锚点元素（就是）实现，在每次点击时页面将被重新加载。<code>React Router</code>提供了<code>&lt;Link&gt;</code>组件用来避免这种状况的发生。当你点击<code>&lt;Link&gt;</code>时，<code>URL</code>会更新，组件会被重新渲染，但是页面不会重新加载</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Link &#125; <span class="keyword">from</span> <span class="string">'react-router-dom'</span></span><br><span class="line"><span class="keyword">const</span> Header = <span class="function"><span class="params">()</span> =&gt;</span> (</span><br><span class="line">  &lt;header&gt;</span><br><span class="line">    &lt;nav&gt;</span><br><span class="line">      &lt;ul&gt;</span><br><span class="line">        &lt;li&gt;<span class="xml"><span class="tag">&lt;<span class="name">Link</span> <span class="attr">to</span>=<span class="string">'/'</span>&gt;</span>Home<span class="tag">&lt;/<span class="name">Link</span>&gt;</span></span>&lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">        &lt;li&gt;&lt;Link to='/</span>roster<span class="string">'&gt;Roster&lt;/Link&gt;&lt;/li&gt;</span></span><br><span class="line"><span class="string">        &lt;li&gt;&lt;Link to='</span>/schedule<span class="string">'&gt;Schedule&lt;/Link&gt;&lt;/li&gt;</span></span><br><span class="line"><span class="string">      &lt;/ul&gt;</span></span><br><span class="line"><span class="string">    &lt;/nav&gt;</span></span><br><span class="line"><span class="string">  &lt;/header&gt;</span></span><br><span class="line"><span class="string">)</span></span><br></pre></td></tr></table></figure>
<ul>
<li><code>&lt;Link&gt;</code>使用<code>&#39;to&#39;</code>参数来描述需要定位的页面。它的值即可是字符串也可是<code>location</code>对象（包含<code>pathname</code>，<code>search</code>，<code>hash</code>与<code>state</code>属性）。如果其值为字符床将会被转换为<code>location</code>对象。</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">Link</span> <span class="attr">to</span>=<span class="string">&#123;&#123;</span> <span class="attr">pathname:</span> '/<span class="attr">roster</span>/<span class="attr">7</span>' &#125;&#125;&gt;</span>Player #7<span class="tag">&lt;/<span class="name">Link</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="十二、Match"><a href="#十二、Match" class="headerlink" title="十二、Match"></a>十二、Match</h2><blockquote>
<p>正如我们上面看到的那样，<code>props.match</code> 可以帮我们获取 <code>userId</code> 和 <code>routes</code></p>
</blockquote>
<ul>
<li><code>match</code> 对象为我们提供了 <code>match.params</code>，<code>match.path</code>，和 <code>match.url</code> 等属性</li>
</ul>
<p><strong>1、match.path vs match.url</strong></p>
<blockquote>
<p>最开始，可能觉得这两者的区别并不明显，控制台经常出现相同的输出，比如，访问 /user</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> UserSubLayout = <span class="function">(<span class="params">&#123; match &#125;</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(match.url)   <span class="comment">// output: "/user"</span></span><br><span class="line">  <span class="built_in">console</span>.log(match.path)  <span class="comment">// output: "/user"</span></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div className=<span class="string">"user-sub-layout"</span>&gt;</span><br><span class="line">      &lt;aside&gt;</span><br><span class="line">        &lt;UserNav /&gt;</span><br><span class="line">      &lt;<span class="regexp">/aside&gt;</span></span><br><span class="line"><span class="regexp">      &lt;div className="primary-content"&gt;</span></span><br><span class="line"><span class="regexp">        &lt;Switch&gt;</span></span><br><span class="line"><span class="regexp">          &lt;Route path=&#123;match.path&#125; exact component=&#123;BrowseUsersPage&#125; /</span>&gt;</span><br><span class="line">          &lt;Route path=&#123;<span class="string">`<span class="subst">$&#123;match.path&#125;</span>/:userId`</span>&#125; component=&#123;UserProfilePage&#125; /&gt;</span><br><span class="line">        &lt;<span class="regexp">/Switch&gt;</span></span><br><span class="line"><span class="regexp">      &lt;/</span>div&gt;</span><br><span class="line">    &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">  )</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br></pre></td></tr></table></figure>
<ul>
<li><code>match</code> 在组件的参数中被解构，意思就是我们可以使用 <code>match.path</code> 代替 <code>props.match.path</code></li>
<li>虽然我们看不到什么明显的差异，但需要明白的是 <code>match.url</code> 是浏览器 <code>URL</code> 的一部分，<code>match.path</code> 是我们为 <code>router</code> 书写的路径</li>
</ul>
<p><strong>2、如何选择</strong></p>
<ul>
<li>如果我们是构建 route 路径，那么肯定使用 match.path</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> UserComments = <span class="function">(<span class="params">&#123; match &#125;</span>) =&gt;</span></span><br><span class="line">  &lt;div&gt;</span><br><span class="line">    UserId: &#123;match.params.userId&#125;</span><br><span class="line">  &lt;<span class="regexp">/div&gt;;</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">const UserSettings = (&#123; match &#125;) =&gt;</span></span><br><span class="line"><span class="regexp">  &lt;div&gt;</span></span><br><span class="line"><span class="regexp">    UserId: &#123;match.params.userId&#125;</span></span><br><span class="line"><span class="regexp">  &lt;/</span>div&gt;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> UserProfilePage = <span class="function">(<span class="params">&#123; match &#125;</span>) =&gt;</span></span><br><span class="line">  &lt;div&gt;</span><br><span class="line">    User Profile:</span><br><span class="line">    &lt;Route path=&#123;<span class="string">`<span class="subst">$&#123;match.url&#125;</span>/comments`</span>&#125; component=&#123;UserComments&#125; /&gt;</span><br><span class="line">    &lt;Route path=&#123;<span class="string">`<span class="subst">$&#123;match.path&#125;</span>/settings`</span>&#125; component=&#123;UserSettings&#125; /&gt;</span><br><span class="line">  &lt;<span class="regexp">/div&gt;;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>然后，我们按下面方式来访问</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">/user/<span class="number">5</span>/comments</span><br><span class="line">/user/<span class="number">5</span>/settings</span><br></pre></td></tr></table></figure>
<ul>
<li>实践后，我们发现，访问 comments 返回 undefined，访问 settings 返回 5</li>
</ul>
<p><strong>3、避免 Match 冲突</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> UserSubLayou = <span class="function">(<span class="params">&#123; match &#125;</span>) =&gt;</span></span><br><span class="line">  &lt;div className=<span class="string">"user-sub-layout"</span>&gt;</span><br><span class="line">    &lt;aside&gt;</span><br><span class="line">      &lt;UserNav /&gt;</span><br><span class="line">    &lt;<span class="regexp">/aside&gt;</span></span><br><span class="line"><span class="regexp">    &lt;div className="primary-content"&gt;</span></span><br><span class="line"><span class="regexp">      &lt;Switch&gt;</span></span><br><span class="line"><span class="regexp">        &lt;Route exact path=&#123;match.path&#125; component=&#123;BrowseUsersPage&#125; /</span>&gt;</span><br><span class="line">        &lt;Route path=&#123;<span class="string">`<span class="subst">$&#123;match.path&#125;</span>/add`</span>&#125; component=&#123;AddUserPage&#125; /&gt;</span><br><span class="line">        &lt;Route path=&#123;<span class="string">`<span class="subst">$&#123;match.path&#125;</span>/:userId/edit`</span>&#125; component=&#123;EditUserPage&#125; /&gt;</span><br><span class="line">        &lt;Route path=&#123;<span class="string">`<span class="subst">$&#123;match.path&#125;</span>/:userId`</span>&#125; component=&#123;UserProfilePage&#125; /&gt;</span><br><span class="line">      &lt;<span class="regexp">/Switch&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/</span>div&gt;</span><br><span class="line">  &lt;<span class="regexp">/div&gt;;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>我们使用 <code>${match.path}/:userId(\\d+)</code>作为 <code>UserProfilePage</code> 对应的 <code>path</code>，保证 <code>:userId</code> 是一个数字，可以避免与 <code>/users/add</code>的冲突，这样，将其所在的 <code>&lt;Route&gt;</code> 丢到最前面去也能正常访问 <code>add</code> 页面  </p>
</blockquote>
<h2 id="十三、Authorized-Route"><a href="#十三、Authorized-Route" class="headerlink" title="十三、Authorized Route"></a>十三、Authorized Route</h2><blockquote>
<p>在应用程序中限制未登录的用户访问某些路由是非常常见的，还有对于授权和未授权的用户 UI 也可能大不一样，为了解决这样的需求，我们可以考虑为应用程序设置一个主入口</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">App</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">  render() &#123;</span><br><span class="line"><span class="keyword">return</span> (</span><br><span class="line">      &lt;Provider store=&#123;store&#125;&gt;</span><br><span class="line">        &lt;BrowserRouter&gt;</span><br><span class="line">          &lt;Switch&gt;</span><br><span class="line">            &lt;Route path=<span class="string">"/auth"</span> component=&#123;UnauthorizedLayout&#125; /&gt;</span><br><span class="line">            &lt;AuthorizedRoute path=<span class="string">"/app"</span> component=&#123;PrimaryLayout&#125; /&gt;</span><br><span class="line">          &lt;<span class="regexp">/Switch&gt;</span></span><br><span class="line"><span class="regexp">        &lt;/</span>BrowserRouter&gt;</span><br><span class="line">      &lt;<span class="regexp">/Provider&gt;</span></span><br><span class="line"><span class="regexp">    )</span></span><br><span class="line"><span class="regexp">  &#125;</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>现在，我们首先会去选择应用程序在哪个顶级布局中，比如，<code>/auth/login</code> 和 <code>/auth/forgot-password</code> 肯定在 <code>UnauthorizedLayout</code> 中，另外，当用户登陆时，我们将判断所有的路径都有一个 /app 前缀以确保是否登录。如果用户访问 <code>/app</code> 开头的页面但并没有登录，我们将会重定向到登录页面</p>
</blockquote>
<h2 id="十四、-lt-Link-gt"><a href="#十四、-lt-Link-gt" class="headerlink" title="十四、&lt;Link&gt;"></a>十四、<code>&lt;Link&gt;</code></h2><blockquote>
<p>和之前版本没太大区别，重点看下组件属性</p>
</blockquote>
<ul>
<li><code>to（string/object）</code>：要跳转的路径或地址；</li>
<li><code>replace（bool）</code>：为 <code>true</code> 时，点击链接后将使用新地址替换掉访问历史记录里面的原地址；为 <code>false</code> 时，点击链接后将在原有访问历史记录的基础上添加一个新的纪录。默认为<code>false</code></li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// Link组件示例</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// to为string</span></span><br><span class="line">&lt;Link to=<span class="string">"/about"</span>&gt;关于&lt;<span class="regexp">/Link&gt;</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">/</span><span class="regexp">/ to为obj</span></span><br><span class="line"><span class="regexp">&lt;Link to=&#123;&#123;</span></span><br><span class="line"><span class="regexp">  pathname: '/</span>courses<span class="string">',</span></span><br><span class="line"><span class="string">  search: '</span>?sort=name<span class="string">',</span></span><br><span class="line">  hash: '#the-hash',</span><br><span class="line">  state: &#123; <span class="attr">fromDashboard</span>: <span class="literal">true</span> &#125;</span><br><span class="line">&#125;&#125;/&gt;</span><br><span class="line"></span><br><span class="line"><span class="comment">// replace </span></span><br><span class="line">&lt;Link to=<span class="string">"/courses"</span> replace /&gt;</span><br></pre></td></tr></table></figure>
<p><strong><code>&lt;NavLink&gt;</code></strong></p>
<blockquote>
<p><code>&lt;NavLink&gt;</code>是<code>&lt;Link&gt;</code> 的一个特定版本, 会在匹配上当前 <code>URL</code> 的时候会给已经渲染的元素添加样式参数，组件属性</p>
</blockquote>
<ul>
<li><code>activeClassName（string）</code>：设置选中样式，默认值为<code>active</code>；</li>
<li><code>activeStyle（object）</code>：当元素被选中时, 为此元素添加样式；</li>
<li><code>exact（bool）</code>：为 <code>true</code> 时, 只有当地址完全匹配 <code>class</code> 和 <code>style</code> 才会应用；</li>
<li><code>strict（bool）</code>：为 <code>true</code> 时，在确定位置是否与当前 <code>URL</code> 匹配时，将考虑位置 - <code>pathname</code> 后的斜线；</li>
<li><code>isActive（func）</code>：判断链接是否激活的额外逻辑的功能</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 用法</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// activeClassName选中时样式为selected</span></span><br><span class="line">&lt;NavLink</span><br><span class="line">  to=<span class="string">"/faq"</span></span><br><span class="line">  activeClassName=<span class="string">"selected"</span></span><br><span class="line">&gt;FAQs&lt;<span class="regexp">/NavLink&gt;</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">/</span><span class="regexp">/ 选中时样式为activeStyle的样式设置</span></span><br><span class="line"><span class="regexp">&lt;NavLink</span></span><br><span class="line"><span class="regexp">  to="/</span>faq<span class="string">"</span></span><br><span class="line"><span class="string">  activeStyle=&#123;&#123;</span></span><br><span class="line"><span class="string">    fontWeight: 'bold',</span></span><br><span class="line"><span class="string">    color: 'red'</span></span><br><span class="line"><span class="string">   &#125;&#125;</span></span><br><span class="line"><span class="string">&gt;FAQs&lt;/NavLink&gt;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">// 当event id为奇数的时候，激活链接</span></span><br><span class="line"><span class="string">const oddEvent = (match, location) =&gt; &#123;</span></span><br><span class="line"><span class="string">  if (!match) &#123;</span></span><br><span class="line"><span class="string">    return false</span></span><br><span class="line"><span class="string">  &#125;</span></span><br><span class="line"><span class="string">  const eventID = parseInt(match.params.eventID)</span></span><br><span class="line"><span class="string">  return !isNaN(eventID) &amp;&amp; eventID % 2 === 1</span></span><br><span class="line"><span class="string">&#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&lt;NavLink</span></span><br><span class="line"><span class="string">  to="</span>/events/<span class="number">123</span><span class="string">"</span></span><br><span class="line"><span class="string">  isActive=&#123;oddEvent&#125;</span></span><br><span class="line"><span class="string">&gt;Event 123&lt;/NavLink&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="十五、-lt-Switch-gt"><a href="#十五、-lt-Switch-gt" class="headerlink" title="十五、&lt;Switch&gt;"></a>十五、<code>&lt;Switch&gt;</code></h2><blockquote>
<p>该组件用来渲染匹配地址的第一个<code>&lt;Route&gt;</code>或者<code>&lt;Redirect&gt;</code>。那么它与使用一堆<code>route</code>又有什么区别呢</p>
</blockquote>
<ul>
<li><code>&lt;Switch&gt;</code>的独特之处是独它仅仅渲染一个路由。相反地，每一个包含匹配地址(<code>location</code>)的<code>&lt;Route&gt;</code>都会被渲染</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&lt;Switch&gt;</span><br><span class="line">  &lt;Route exact path=<span class="string">"/"</span> component=&#123;Home&#125;/&gt;</span><br><span class="line">  &lt;Route path=<span class="string">"/about"</span> component=&#123;About&#125;/&gt;</span><br><span class="line">  &lt;Route path=<span class="string">"/:user"</span> component=&#123;User&#125;/&gt;</span><br><span class="line">  &lt;Route component=&#123;NoMatch&#125;/&gt;</span><br><span class="line">&lt;<span class="regexp">/Switch&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>现在，如果我们处于<code>/about</code>，<code>&lt;Switch&gt;</code>将开始寻找匹配的<code>&lt;Route&gt;</code>。<code>&lt;Route path=&quot;/about&quot;/&gt;</code> 将被匹配， <code>&lt;Switch&gt;</code>将停止寻找匹配并渲染<code>&lt;About&gt;</code>。同样，如果我们处于<code>/michael</code>，<code>&lt;User&gt;</code>将被渲染</p>
</blockquote>
<h2 id="十六、更多参考"><a href="#十六、更多参考" class="headerlink" title="十六、更多参考"></a>十六、更多参考</h2><ul>
<li><a href="https://reacttraining.com/react-router/web/guides/philosophy" target="_blank" rel="noopener">https://reacttraining.com/react-router/web/guides/philosophy</a></li>
</ul>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2017/11/19/redux-study-combine-react-and-redux/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2017/11/20/react-study-Immutable/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
